package com.sgcc.fj.pmos.mobileapp.presenter;

import android.text.TextUtils;
import android.util.Log;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.sgcc.fj.pmos.common.base.BasePresenter;
import com.sgcc.fj.pmos.common.http.HttpInterConst;
import com.sgcc.fj.pmos.common.http.HttpRequestUtils;
import com.sgcc.fj.pmos.common.http.MvcNetCallback;
import com.sgcc.fj.pmos.common.http.MvpNetCallback;
import com.sgcc.fj.pmos.common.sm.SM3;
import com.sgcc.fj.pmos.common.utils.BurialPointUtils;
import com.sgcc.fj.pmos.common.utils.SignUtils;
import com.sgcc.fj.pmos.common.utils.UserManager;
import com.sgcc.fj.pmos.mobileapp.bean.CodeBean;
import com.sgcc.fj.pmos.mobileapp.bean.ConfigBean;
import com.sgcc.fj.pmos.mobileapp.bean.DoLoginReleaseBean;
import com.sgcc.fj.pmos.mobileapp.bean.LoginReleaseTokenBean;
import com.sgcc.fj.pmos.mobileapp.bean.QueryUserFlowBean;
import com.sgcc.fj.pmos.mobileapp.bean.StringDataBean;
import com.sgcc.fj.pmos.mobileapp.bean.UserInfoBean;
import com.sgcc.fj.pmos.mobileapp.contract.LoginContract;
import com.sgcc.fj.pmos.mobileapp.utils.SmUtils;
import com.sgcc.ln.pmos.common.interceptor.SignInterceptor;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

public class LoginPresenter extends BasePresenter<LoginContract.View> implements LoginContract.Presenter {
    String membersName;
    String membersId;
    String username;

    @Override
    public void startLogin(String username, String password) {
        Map<String, Object> params = new HashMap<>();
        HttpRequestUtils.getInstance().request(params, HttpInterConst.LOGIN_GET_KEY, new MvcNetCallback<CodeBean>(true) {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                // 失败回调 判断界面是否销毁
            }

            @Override
            public void onResponse(CodeBean response, int id) {
                super.onResponse(response, id);
                if (response != null && response.getStatus() == 0) {
                    try {
//                        if (HttpInterConst.isRelease) {
                        doLoginRelease(response.getData().getSecureCode(), response.getData().getSecureKey(), username, password);
//                        } else {
//                            doLogin(response.getData().getSecureCode(), response.getData().getSecureKey(), username, password);
//                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    public void doLoginRelease(String secureCode, String secureKey, String username, String password) throws Exception {
        Map<String, Object> params = new HashMap<>();
        long currentTimeMillis = System.currentTimeMillis();
        String credential = SmUtils.encryptSM2(password, secureKey);
        this.username = username;
        SM3 sm3Dpct = new SM3();
        Map map = new HashMap();
        map.put("identifier", username);
        map.put("credential", credential);
        map.put("identityType", "UN");
        map.put("ot", currentTimeMillis);
        map.put("appId", "618101657204559872");
        map.put("secureCode", secureCode);
        String data = SignUtils.sortParams(map);
        String key = sm3Dpct.SM3Digest(data);

        params.put("secretKey", key);
        params.put("identifier", username);
        params.put("credential", credential);
        params.put("identityType", "UN");
        params.put("ot", currentTimeMillis);
        params.put("secureCode", secureCode);
        params.put("appId", "618101657204559872");

        HttpRequestUtils.getInstance().request(params, HttpInterConst.LOGIN_RELEASE, new MvpNetCallback<String>(getView(), true) {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                // 失败回调 判断界面是否销毁
                if (!isViewAttached()) {
                    return;
                }
                getView().LoginFailed();
            }

            @Override
            public void onResponse(String response, int id) {
                super.onResponse(response, id);
                if (!isViewAttached()) {
                    return;
                }
                DoLoginReleaseBean baseResponse = GsonUtils.fromJson(response, DoLoginReleaseBean.class);
                if (baseResponse != null) {
                    if (baseResponse.getStatus() == 0) {
                        LoginReleaseTokenBean loginReleaseTokenBean = GsonUtils.fromJson(response, LoginReleaseTokenBean.class);
                        if (loginReleaseTokenBean.getData() != null) {
                            if (loginReleaseTokenBean.getData().getAppToken() != null) {
                                SignInterceptor.Authorization = String.format("X-Ticket=%s; Admin-Token20090=%s", loginReleaseTokenBean.getData().getAppToken().getToken(), loginReleaseTokenBean.getData().getAppToken().getToken());
                                String membersId = "";
                                if (null != loginReleaseTokenBean.getData().getSubjectsInfo()) {
                                    membersId = loginReleaseTokenBean.getData().getSubjectsInfo().getMembersId();
                                    membersName = loginReleaseTokenBean.getData().getSubjectsInfo().getMembersName();
                                }
                                if (TextUtils.isEmpty(membersName)) {
                                    new XPopup.Builder(ActivityUtils.getTopActivity())
                                            .dismissOnBackPressed(false)
                                            .dismissOnTouchOutside(false)
                                            .asConfirm("温馨提示", "账号企业信息不完整，请完善企业信息后再登录！", new OnConfirmListener() {
                                                @Override
                                                public void onConfirm() {
                                                    UserManager.logout();
                                                }
                                            }).show();
                                } else {
                                    userInfo(membersId, username);
                                }
                            } else {
                                if (!TextUtils.isEmpty(loginReleaseTokenBean.getMessage())) {
                                    ToastUtils.showShort(loginReleaseTokenBean.getMessage());
                                }
                            }
                        }
                    } else {
                        if (!TextUtils.isEmpty(baseResponse.getMessage())) {
                            ToastUtils.showShort(baseResponse.getMessage());
                        }
                    }
                } else {
                    getView().LoginFailed();
                }
            }

        });
    }

    public void userInfo(String membersId, String username) {
        Map<String, Object> params = new HashMap<>();
        params.put("local", "false");
        params.put("_t", System.currentTimeMillis());
        HttpRequestUtils.getInstance().request(params, HttpInterConst.USERINFO, new MvpNetCallback<UserInfoBean>(getView(), true) {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                // 失败回调 判断界面是否销毁
                if (!isViewAttached()) {
                    return;
                }
                getView().LoginFailed();
            }

            @Override
            public void onResponse(UserInfoBean response, int id) {
                super.onResponse(response, id);
                if (!isViewAttached()) {
                    return;
                }
                if (response != null) {
                    if (response.getStatus() == 0) {
                        if (null != response.getData()) {
                            if (null != response.getData().getExtend()) {
                                //membersType为20时，是电力用户，30售电公司，10发电企业,cfcaLogin是否绑定UKEY，
                                // ture时需要调取接口查询UKEY授权情况，判断是否可以登录
                                if (!"20".equals(response.getData().getExtend().getMembersType())) {
                                    ToastUtils.showLong("当前用户类型暂不支持在app上登录");
                                    return;
                                }
                            }
                            //0用户不需要UKEY登录，1已经授权可以登录，2拒绝授权不能登录，3提示前往PC端进行授权
//                            if (null == response.getData().getCfcaAuthorizeFlag()) {
//                                ToastUtils.showLong("系统异常");
//                                return;
//                            }
//                            //等于2或者3 就弹出提示
//                            if (response.getData().getCfcaAuthorizeFlag() == 2 || response.getData().getCfcaAuthorizeFlag() == 3) {
//                                new XPopup.Builder(ActivityUtils.getTopActivity())
//                                        .dismissOnTouchOutside(false)
//                                        .asCustom(new PackageDetails1PopView(ActivityUtils.getTopActivity()))
//                                        .show();
//                                return;
//                            }
                            BurialPointUtils.onBurialPoint(BurialPointUtils.mPoint.LOGIN);
                            UserManager.setUserBean(response.getData());
                            getView().LoginSuccess();
//                            queryUserFlow(membersId, username,response.getData());
                        } else {
                            getView().LoginFailed();
                        }
                    } else {
                        getView().LoginFailed();
                    }
//                    getView().LoginSuccess();
                } else {
                    getView().LoginFailed();
                }
            }

        });
    }

    public void userInfoFlow(String membersId, String username) {
        Map<String, Object> params = new HashMap<>();
        params.put("local", "false");
        params.put("_t", System.currentTimeMillis());
        HttpRequestUtils.getInstance().request(params, HttpInterConst.USERINFO, new MvpNetCallback<UserInfoBean>(getView(), true) {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                // 失败回调 判断界面是否销毁
                if (!isViewAttached()) {
                    return;
                }
                getView().LoginFailed();
            }

            @Override
            public void onResponse(UserInfoBean response, int id) {
                super.onResponse(response, id);
                if (!isViewAttached()) {
                    return;
                }
                if (response != null) {
                    if (response.getStatus() == 0) {
                        if (null != response.getData()) {
                            if (null != response.getData().getExtend()) {
                                //membersType为20时，是电力用户，30售电公司，10发电企业,cfcaLogin是否绑定UKEY，
                                // ture时需要调取接口查询UKEY授权情况，判断是否可以登录
                                if (!response.getData().getExtend().getMembersType().equals("20")) {
                                    ToastUtils.showLong("当前用户类型暂不支持在app上登录");
                                    return;
                                }
                            }
//                            //0用户不需要UKEY登录，1已经授权可以登录，2拒绝授权不能登录，3提示前往PC端进行授权
//                            if (null == response.getData().getCfcaAuthorizeFlag()) {
//                                ToastUtils.showLong("系统异常");
//                                return;
//                            }
//                            //等于2或者3 就弹出提示
//                            if (response.getData().getCfcaAuthorizeFlag() == 2 || response.getData().getCfcaAuthorizeFlag() == 3) {
//                                new XPopup.Builder(ActivityUtils.getTopActivity())
//                                        .dismissOnTouchOutside(false)
//                                        .asCustom(new PackageDetails1PopView(ActivityUtils.getTopActivity()))
//                                        .show();
//                                return;
//                            }
                            BurialPointUtils.onBurialPoint(BurialPointUtils.mPoint.LOGIN);
                            UserManager.setUserBean(response.getData());
                            getView().LoginSuccess();

                        } else {
                            getView().LoginFailed();
                        }
                    } else {
                        getView().LoginFailed();
                    }
//                    getView().LoginSuccess();
                } else {
                    getView().LoginFailed();
                }
            }

        });
    }


    public void queryUserFlow(String membersId, String username) {
        Map<String, Object> params = new HashMap<>();
        params.put("membersId", membersId);
        HttpRequestUtils.getInstance().request(params, HttpInterConst.QUERY_USER_FLOW, new MvpNetCallback<QueryUserFlowBean>(getView(), true) {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                // 失败回调 判断界面是否销毁
                if (!isViewAttached()) {
                    return;
                }
                getView().LoginFailed();
            }

            @Override
            public void onResponse(QueryUserFlowBean response, int id) {
                super.onResponse(response, id);
                if (!isViewAttached()) {
                    return;
                }
                if (response != null) {
                    if (null != response.getData() && response.getData().size() > 0) {
//                        2.审核中（02提交，04受理，06提交，07受理，10通过，11公示，28通过，31待营销审核）
//                        审核驳回（05驳回,12驳回,32营销驳回）
//                        审核通过（29生效）
                        QueryUserFlowBean.Data data = response.getData().get(response.getData().size() - 1);

                        //TODO 测试账号 appyanfa先通过验证
                        if (username.equals("appyanfa")) {
                            data.setState("29");
                        }

                        switch (data.getState()) {
                            case "02":
                            case "04":
                            case "06":
                            case "07":
                            case "10":
                            case "11":
                            case "28":
                            case "31":
                                getView().goRegistered("6");//6审核中，8审核驳回
                                break;
                            case "05":
                            case "12":
                            case "32":
                                getView().goRegistered("8", data.getView());//6审核中，8审核驳回
                                break;
                            case "29":
                                userInfoFlow(membersId, username);
//                                UserManager.setUserBean(userBean);
//                                getView().LoginSuccess();
                                break;
                            default:
                                getView().goRegistered("");//空字符串 工商信息，
                                break;
                        }
                    } else {
                        if (TextUtils.isEmpty(membersName)) {
                            getStep();
                        } else {
                            userInfoFlow(membersId, username);
//                            UserManager.setUserBean(userBean);
//                            getView().LoginSuccess();
                            membersName = "";
                        }

                    }


                } else {

                    getView().LoginFailed();
                }
            }

        });
    }

    public void getStep() {
        Map<String, Object> params = new HashMap<>();
        HttpRequestUtils.getInstance().request(params, HttpInterConst.GETSTEP, new MvpNetCallback<StringDataBean>(getView(), true) {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                // 失败回调 判断界面是否销毁
                if (!isViewAttached()) {
                    return;
                }
                getView().LoginFailed();
            }

            @Override
            public void onResponse(StringDataBean response, int id) {
                super.onResponse(response, id);
                if (!isViewAttached()) {
                    return;
                }
                if (response != null) {
                    if (response.getStatus() == 0 && "Success".equals(response.getMessage())) {
                        getView().goRegistered(response.getData());
                    } else {
                        if (!TextUtils.isEmpty(response.getMessage())) {
                            ToastUtils.showShort(response.getMessage());
                        }
                    }
                } else {
                    getView().LoginFailed();
                }
            }

        });
    }

    public void getVisibilConfig() {
        Map<String, Object> params = new HashMap<>();
        HttpRequestUtils.getInstance().request(params, HttpInterConst.HOME_CONFIGE, new MvpNetCallback<ConfigBean>(getView(), true) {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                if (!isViewAttached()) {
                    return;
                }
                // 失败回调 判断界面是否销毁
                getView().queryVisibilConfigFailed();
            }

            @Override
            public void onResponse(ConfigBean response, int id) {
                super.onResponse(response, id);
                if (!isViewAttached()) {
                    return;
                }
                getView().queryVisibilConfigSuccess(response);
            }
        });

    }

}
